package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeSecondAreaActivity;
import com.epfresh.adapter.SecondKillListAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestEntityPurchase;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.bean.AddCarResponse;
import com.epfresh.bean.CarCntResponse;
import com.epfresh.bean.CountDownTime;
import com.epfresh.bean.ListSecondKill;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.CountDownView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.Activity.RESULT_OK;

/**
 * Created by wzh on 2016/5/4.
 */
@SuppressLint("ValidFragment")
public class SecondListFragment extends BaseFragment implements LoadMoreListView.IXListViewListener , CountDownView.OnCountDownListener {

    LoadMoreListView lvContent;
    ArrayList<ListSecondKill.ContentBean> goodsLists;
    private SecondKillListAdapter adapterGoods;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 10;
    private TagPager tagPager = new TagPager();
    Context mContext;

    String storeId,beginTime,endTime,sysDate;
    int status;
    SecondKillFragment secondKillFragment;

    public SecondKillFragment getSecondKillFragment() {
        return secondKillFragment;
    }

    public void setSecondKillFragment(SecondKillFragment secondKillFragment) {
        this.secondKillFragment = secondKillFragment;
    }

    public SecondListFragment() {
    }
    public SecondListFragment(String storeId, String beginTime,String endTime,int status) {
        this.storeId = storeId;
        this.beginTime = beginTime;
        this.endTime = endTime;
        this.status = status;
    }

    @Override
    public String getBaseTag() {
        return "SecondListFragment";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second_list, container, false);
        mContext = this.getActivity();
        initView(view);
        loadData(tagPager.getNumber());

        return view;
    }
    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }

    CountDownTime cdt;
    CountDownView cdv;
    void initCdv() {
        cdt = new CountDownTime();
        cdt.setStartSubTime(beginTime);//fineRecommendation.getString("beginTime"));
        cdt.setEndSubTime(endTime);//fineRecommendation.getString("endTime"));
        cdt.setSysDate(sysDate);//fineRecommendation.getString("sysDate"));
        Log.e("cdt", "s:" + cdt.getStartSubTime());
        Log.e("cdt", "l:" + cdt.getSysDate());
        Log.e("cdt", "e:" + cdt.getEndSubTime());
        cdt.init();
        long countDownTime = cdt.getCountDownTime();
        if (countDownTime == 0) {//活动已经结束
//                cdv.setVisibility(View.INVISIBLE);
        } else if (countDownTime > 0) {//活动进行中
            cdv.setVisibility(View.VISIBLE);
            cdv.showTimer(cdt, countDownTime, 1000);
        } else if (countDownTime < 0) {
            cdv.setVisibility(View.VISIBLE);
            cdv.showTimer(cdt, countDownTime, 1000);
        }
    }

    void topStatusUpdate(){
        if(status==1){// 1即将开始 2进行中 3 已结束
            tv_hint.setText("即将开始");
            //tv_hint_time.setText("距开始");
        }else if(status==2){
            tv_hint.setText("先下单先得哦");
            rl_info.setBackgroundColor(Color.parseColor("#70CCAD"));
        }else{
            tv_hint.setText("已结束 下场请早");
            cdv.setVisibility(View.INVISIBLE);
        }

    }
    TextView tv_hint;
    View rl_info;
    void initView(View v){
        cdv = (CountDownView)v.findViewById(R.id.cdv);
        cdv.setOnCountDownListener(this);
        rl_info = v.findViewById(R.id.rl_info);
        tv_hint = (TextView)v.findViewById(R.id.tv_hint);
        //TextView tv_hint_time = (TextView)v.findViewById(R.id.tv_hint_time);
        topStatusUpdate();


        lvContent = (LoadMoreListView)  v.findViewById(R.id.lv_content);
        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        mainView =  v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initHeadView(v);
        tagPager.setNumber(0);
        goodsLists = new ArrayList<>();
        adapterGoods = new SecondKillListAdapter(getContext(), goodsLists);
        initGoodsAdapter();
/*
        adapterGoods.setOnCartAddListener(new SecondKillListAdapter.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, ListSecondKill.ContentBean goods,View v) {
                if (type == 1) {//购物车手动输入


                } else if (type == 2) {//添加
                  //  addCartCnt(goods, true);
                } else if (type == 3) {//减少
                   // addCartCnt(goods, false);

                } else if (type == 5) {
                    String id = goods.getProduct().getId();
                    String pId = goods.getPromotionItemId();
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("promotionItemId", pId);
                    intent.putExtra("id", id + "");
                    startActivity(intent);

                }
            }
        });*/

//        adapter = new OrderAdapter(context, goodsLists, R.layout.item_center_search);

        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long l) {
                if (i < goodsLists.size()) {
                    ListSecondKill.ContentBean listGoods = SecondListFragment.this.goodsLists.get(i);
                    //String id = listGoods.getId();
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("storeId", listGoods.getProduct().getStoreId());
                    intent.putExtra("id", listGoods.getProduct().getId());
                    intent.putExtra("promotionItemId", listGoods.getPromotionItemId());

                    startActivity(intent);
                }
            }
        });
        lvContent.setXListViewListener(this);
        lvContent.setAdapter(adapterGoods);
        View rlNoDate =  v.findViewById(R.id.rl_nodate);
        lvContent.setEmptyView(rlNoDate);
    }
    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        lvContent.resetNoMore();
        refreshFlag = true;
        loadData(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }

    void loadData(int page){
        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        String seckillStoreId = null;
        if (getAppActivity() != null && getAppActivity() instanceof HomeSecondAreaActivity){
            seckillStoreId = ((HomeSecondAreaActivity)getAppActivity()).seckillStoreId;
        }
        map.put("storeId",seckillStoreId);
        Log.e("storeId____",storeId+"");
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("pageNumber", page + "");
        map.put("pageSize", PAGE_SIZE + "");
        entity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_promotion_seckillPage);
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_promotion_seckillPage;
        requestTag.action = page;
        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }


    private void initGoodsAdapter (){
        adapterGoods.setOnAddClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

/*                if (!isAcceptOrder) {
                    T.toast("暂不接单");
                } else {*/
//                    addCart(listGoods.get(i));
                    ListSecondKill.ContentBean goods = goodsLists.get(i);
                    updateCartCnt(Double.parseDouble(goods.getProduct().getProductSpecPrice().getMoq()),goods);
  //              }
            }
        });

        adapterGoods.setOnCartAddListener(new SecondKillListAdapter.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, ListSecondKill.ContentBean goods,View v) {
                if (type == 1) {//购物车手动输入
                    openDialog(type, position, goods);


                } else if (type == 2) {//添加
                    addCartCnt(goods, true);
                } else if (type == 3) {//减少
                    addCartCnt(goods, false);

                } else if (type == 5) {
                    String id = goods.getProduct().getId();
                    String pId = goods.getPromotionItemId();
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    intent.putExtra("storeId", goods.getProduct().getStoreId());
                    intent.putExtra("promotionItemId", pId);
                    intent.putExtra("id", id + "");
                    startActivity(intent);

                }
            }
        });

        adapterGoods.setOnTextChangeListener(new SecondKillListAdapter.OnTextChangeListener() {

            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, ListSecondKill.ContentBean cartGood) {
                openDialog(groupPosition, childPosition, cartGood);

            }
        });
        adapterGoods.setOnChangeListener(new SecondKillListAdapter.OnTextChangeListener() {
            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, ListSecondKill.ContentBean cartGood) {
                //calTotalPrice(adapter.calAllCheckedStatus());
//                cntCart(cartGood.getId() + "", cartGood.getProductCount(), lastCnt);
                updateCartCnt(lastCnt,cartGood);
            }
        });

    }

    public void openDialog(int groupPosition, int childPosition, final  ListSecondKill.ContentBean cartGood) {
        if (getActivity() == null) {
            return;
        }
        final Dialog dialog = new Dialog(getContext(), R.style.no_title_dialog);

        dialog.setContentView(R.layout.dialog_cart_add);
        ImageView ivAdd = (ImageView) dialog.findViewById(R.id.iv_add);
        ImageView ivRemove = (ImageView) dialog.findViewById(R.id.iv_remove);

        final EditText ed = (EditText) dialog.findViewById(R.id.ed_price);

        ed.setText(FormatUtil.subZeroAndDot(cartGood.getCount() + ""));
        ed.setSelection(ed.length());
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 999999;
        ed.setFilters(new InputFilter[]{cashierInputFilter});
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getProduct().getMoq();
                double incr =  cartGood.getProduct().getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;

               // if (cartGood.getWholeSalesType() == 1) {

                    if (FormatUtil.remainderZero(amount,cartGood.getQuantityPerAccount())>0){
                        amount = cartGood.getQuantityPerAccount();
                    }

//                    if (amount > cartGood.getMaxPlaceOrderValue()) {
//                        amount = cartGood.getMaxPlaceOrderValue();
//                    }
//                    amount += incr;
                    amount = FormatUtil.countAdd(amount,incr);
//                    if (amount > cartGood.getMaxPlaceOrderValue()) {
//                        amount = cartGood.getMaxPlaceOrderValue();
//                    }
                    if (FormatUtil.remainderZero(amount,cartGood.getQuantityPerAccount())>0){
                        amount = cartGood.getQuantityPerAccount();
                    }

               /* } else {
                    amount = FormatUtil.countAdd(amount,incr);
                }*/
                cartGood.setCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
                if (amount == cartGood.getQuantityPerAccount()) {
                    T.toast("超出限额数量，请修改");
                }
            }
        });
        ivRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = ed.getText().toString();
                double min = cartGood.getProduct().getMoq();
                double incr =  cartGood.getProduct().getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                double amount = cnt;
//                if (cartGood.getWholeSalesType() == 1) {
                if (amount < min) {
                    amount = min;
                }

                amount= FormatUtil.countSubtract(amount,incr);
                if (amount < min) {
                    amount = min;
                }
//                } else {
//                    amount--;
//                    if (amount < 1) {
//                        amount = 1;
//                    }
//                }
                cartGood.setCount(amount);
                ed.setText(FormatUtil.subZeroAndDot(amount + ""));
            }
        });
        dialog.findViewById(R.id.negativeButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.positiveButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                double productCount = cartGood.getCount();
                String s = ed.getText().toString();
                double min = cartGood.getProduct().getMoq();
                double incr =  cartGood.getProduct().getIncr();
                double cnt = min;
                Log.d("cnt", "s:" + s);
                if (s.length() > 0) {
                    cnt = Double.valueOf(s);
                }
                if (cnt < 0.01 || cnt < min) {
                    T.toast("不能少于"+FormatUtil.subZeroAndDot(min+""));
                    cnt = FormatUtil.countFormat(cnt,incr,min);
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }
              //  if (cartGood.getWholeSalesType() == 1) {
                /*    Log.d("cnt", "cnt:" + cnt);
                    Log.d("cnt", "cnt2:" + cartGood.getMinPlaceOrderValue());
                    Log.d("cnt", "cnt3:" + cartGood.getMaxPlaceOrderValue());
*/
                    if (cnt > cartGood.getQuantityPerAccount()) {
                        T.toast("超过限额数量，请修改");
                        cnt = FormatUtil.countFormat(cartGood.getQuantityPerAccount(),incr,min);

                        ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                        ed.setSelection(ed.getText().length());
                        return;
                    }
              //  }
                incr = incr < 0.01 ? min : incr;

                if (FormatUtil.isRemainder(cnt,incr,min)) {
                    cnt = FormatUtil.countFormat(cnt,incr,min);
                    Log.e("cnt:","cnt:"+FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setText(FormatUtil.subZeroAndDot(cnt + ""));
                    ed.setSelection(ed.getText().length());
                    return;
                }

                cartGood.setCount(cnt);
//                cntCart(cartGood.getId() + "", cnt, productCount);
                updateCartCnt(cnt,cartGood);
                adapterGoods.notifyDataSetChanged();
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), 0);
                }
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {

            }
        });

        dialog.show();

    }



    public void addCartCnt(ListSecondKill.ContentBean goods, boolean isAdd) {
        double min = Double.parseDouble(goods.getProduct().getProductSpecPrice().getMoq());
        double incr = goods.getProduct().getIncr();
        double cnt = goods.getCount();
        double amount = cnt;


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }

//        if (FormatUtil.remainderZero(amount, goods.getProduct().getInventory()) > 0) {
//            amount = goods.getProduct().getInventory();
//            T.toast("库存不够");
//        }
        if (isAdd && FormatUtil.remainderZero(amount, Double.parseDouble(goods.getProduct().getProductSpecPrice().getMoq())) < 0) {
            amount = min;
        }


        if (!isAdd && (FormatUtil.remainderZero(amount, 0) <= 0 || FormatUtil.remainderZero(amount, min) < 0)){
            amount = 0;
            updateCartCnt(amount, goods);
            return;
        }

//        amount = FormatUtil.countFormat(amount, incr, min);
        amount = FormatUtil.countFormat(amount, incr, min, goods.getProduct().getInventory());
        updateCartCnt(amount, goods);

    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    OnRequestListener<ListSecondKill> onRequestListener = new OnRequestListener<ListSecondKill>() {
        @Override
        public ListSecondKill jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, ListSecondKill.class);

        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.product_no, "网络问题,请稍后重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.product_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<ListSecondKill> response, Object tag) {

            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            //页面第一次调用网络请求接口并成功
            if (requestSucceedCount == 0) {
                showMainView();
            }
            requestSucceedCount++;

            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                goodsLists.clear();
            }
            ListSecondKill orderResponse = response.getResponseElement();
            sysDate = orderResponse.getResponseTime();//responseTime
            Log.e("sysDate:","________"+sysDate);

            if(status == 1||status==2){
                initCdv();
            }

            List<ListSecondKill.ContentBean> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.isLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            goodsLists.addAll(content);
            if(goodsLists.size()==0){
                showExceptionView(R.mipmap.product_no,"没有商品",1);
                return;
            }else{
                showMainView();
            }
            adapterGoods.notifyDataSetChanged();
            if (orderResponse.getNumber() == 0) {
                if (resumeFlag) {
                    resumeFlag = false;
                } else {
                    lvContent.setSelection(0);
                }
            }
            updateViewStatus(requestTag);
            if(status == 2)
                requestCount();

        }
    };
    @Override
    public void onResume() {
        super.onResume();
    }
    boolean resumeFlag = false;

    public void intoFresh(){
        showProgressView();
        refresh();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 0x001) {
            intoFresh();
        }
    }


    public void requestCount() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt);

//        re.putParameter("storeId", storeDetail.getId());
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("wholeSalesType", "1");
        Log.e("购物车商品数量接口开始","______");
        ApplicationHelper.getInstance().requestSilent(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_cnt, onCartCntRequestListener);
    }


    OnRequestListener<CarCntResponse> onCartCntRequestListener = new OnRequestListener<CarCntResponse>() {
        @Override
        public CarCntResponse jsonToObj(String s) {
            return new Gson().fromJson(s, CarCntResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

        }

        @Override
        public void onStart(Object o) {

        }

        @Override
        public void onResponse(ResponseEntity<CarCntResponse> responseEntity, Object o) {
//            dcCnt = responseEntity.getResponseElement();
            carCntResponse = responseEntity.getResponseElement();
            if (carCntResponse != null){
                carCntResponse.init();
            }
            Log.e("购物车商品数量接口执行成功","______");

            updateCnt();
        }
    };

    CarCntResponse carCntResponse;

    public void updateCnt() {

        if (carCntResponse != null) {

            if (goodsLists != null) {
                for (int i = 0; i < goodsLists.size(); i++) {
                    ListSecondKill.ContentBean item = goodsLists.get(i);
                    Log.e("购物车商品数量接口执行成功","______");

                    goodsLists.get(i).setCount(carCntResponse.getGoodsCount(item.getIdPlus()));
                    adapterGoods.notifyDataSetChanged();
                    Log.e("listGoods", "cnt:" + item.getCount() + "---id:" + item.getProduct().getId());
                }
            }

            if (adapterGoods != null) {
                adapterGoods.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (cdv != null) {
            cdv.finishTimer();
        }
    }

    OnRequestListener<AddCarResponse> onCntRequestListener = new OnRequestListener<AddCarResponse>() {
        @Override
        public AddCarResponse jsonToObj(String s) {
            return new Gson().fromJson(s, AddCarResponse.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof ListSecondKill.ContentBean) {
                    ListSecondKill.ContentBean goods = (ListSecondKill.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
                        goods.setCount((Double) arg2);
                        adapterGoods.notifyDataSetChanged();

                        T.toast(goods.getProduct().getTitle()+" 添加购物车失败");
                    }
                }
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            hideProgressDialog();
            RequestTag tag = null;
//            if (i / 10 == 40){
//                T.toast((String) o);
//            }
            if (o1 instanceof RequestTag) {
                tag = (RequestTag) o1;
                String arg1 = tag.arg1;
                Object arg2 = tag.arg2;
                Object o2 = tag.tag;
                if (arg1 != null && o2 != null && o2 instanceof ListSecondKill.ContentBean) {
                    ListSecondKill.ContentBean goods = (ListSecondKill.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (arg2 != null && arg2 instanceof Double) {
                        goods.setCount((Double) arg2);
                        adapterGoods.notifyDataSetChanged();

                        if (i / 100 != 4){
                            T.toast(goods.getProduct().getTitle()+" 添加购物车失败");
                        }
                    }
                }
            }
        }

        @Override
        public void onStart(Object o) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<AddCarResponse> responseEntity, Object o) {
            hideProgressDialog();
            AddCarResponse responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {
                DataManager.getInstance().oftenListReFresh = true;

                RequestTag tag = null;
                if (o instanceof RequestTag) {
                    tag = (RequestTag) o;
                    String arg1 = tag.arg1;
                    Object o2 = tag.tag;
                    if (arg1 != null && o2 != null && o2 instanceof ListSecondKill.ContentBean) {
                        ListSecondKill.ContentBean goods = (ListSecondKill.ContentBean) o2;
//                        BigDecimal a = new BigDecimal(arg1).setScale(2, BigDecimal.ROUND_HALF_UP);
                        goods.setCount(responseElement.getProductCnt());
                        //goods.setShoppingCarId(responseElement.getShoppingCarId());
//                        DataManager.getInstance().setCartCntStatus(responseElement.getshoppingCarCnt());
                        DataManager.getInstance().updateCartCnt();

                        if (carCntResponse == null){
                            adapterGoods.notifyDataSetChanged();
                        }else {

                            carCntResponse.putCategoryCount(responseElement.getCategoryId(),responseElement.getCategoryCnt());
                            carCntResponse.putTopCategoryCount(responseElement.getTopCategoryId(),responseElement.getTopCategoryCnt());
                            carCntResponse.putGoodsCount(goods.getIdPlus(),responseElement.getProductCnt());
                            updateCnt();
                        }

                        adapterGoods.notifyDataSetChanged();
                        ((HomeSecondAreaActivity)getActivity()).updateCount(DataManager.getInstance().getCartCnt());

//                        dcAdapter.notifyDataSetChanged();

                    }
                }


            }
        }
    };

    /*CartHelper cartHelper = new CartHelper();
    public void reqCartCnt(double productCount, ListGoods goods) {
        if (goods == null){
            return;
        }

        if (goods != null) {
            goods.setCount(productCount);
            adapterGoods.notifyDataSetChanged();
        }
        if (!cartHelper.checkIsCartRequesting(goods)){
            updateCartCnt(productCount,goods);
        }else {

        }
    }

    public void responseCartCnt(boolean isFail,ListGoods goods,double cnt){
        if (isFail){
            cartHelper.responseCartFail(goods);
        }else {
            cartHelper.responseCartSuccess(goods,cnt);
        }
    }
*/
    public void updateCartCnt(double productCount, ListSecondKill.ContentBean goods) {
        double count = goods.getCount();
        if (goods != null) {
            goods.setCount(productCount);
            adapterGoods.notifyDataSetChanged();
        }
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_cart_add);

//        re.putParameter("shoppingCarId",null);
        //re.putParameter("productUnitPrice", goods.getProduct().getPriceOnly());
        re.putParameter("specId", goods.getProduct().getId());
//        re.putParameter("salesType", goods.getProduct().getType());
//        re.putParameter("versionId", goods.getProduct().getLastSnapshotId());
//        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        re.putParameter("count", productCount);
//        re.putParameter("accountId", ApplicationHelper.getInstance().getUser().getAccountId());
        re.putParameter("specPromotionItemId", goods.getPromotionItemId());
//        re.putParameter("promotionType", "2");
//        re.putParameter("promotionId", goods.getProduct().getPromotionId());
//        re.putParameter("productUnitPrice",goods.getPrice());


        RequestTag tag = new RequestTag();
        tag.tag = goods;
//        tag.tag = "appOrder/updateShoppingCarProductCount";
        tag.arg1 = productCount + "";
        tag.arg2 = count;
//        tag.arg2 = goods;
        request(re, tag, onCntRequestListener);

    }

    @Override
    public void onCountDownListener(boolean isFinish){
        if(isFinish){
            if(secondKillFragment!=null){
                //((HomeSecondAreaActivity)getActivity()).requestTimeList();
                (secondKillFragment).requestTimeList();
            }else {
                refresh();
                if(status == 1){
                    status=2;
                    return;
                }else if(status==2){
                    status = 3;
                }
                topStatusUpdate();

            }
        }
    }

}